import { reactive, watch } from 'vue'

import { getMetaDataState } from './state/state-meta-data'

// 定义查询需要的 meta
const findMeta = reactive({
  moduleId: 142,
  quickFind: [],
  allFind: [],
  customer: {},
  findKind:{},
  'label-width': 100,
  'finditem-width': 300,
  customerDefault: 100,
  itemMeta: {}
})

// 字段单独的meta
const colMeta = reactive({})

/**
 * 创建字段的 meta
 */
export const toMetaFind = () => {
  const state = getMetaDataState()
  // const { sheetNames, current } = state

  const _toMetaCol = (cols) => {
    // 清空
    
    for(const key in colMeta) {
      delete colMeta[key]
      delete findMeta.itemMeta[key]
    }
    findMeta.quickFind.length = 0
    findMeta.allFind.length = 0

    // 遍历
    cols.forEach(col => {
      const meta = {
        columnId: col.columnId,
        colName: col.colName,
        label: col.cnName,
        controlType: col.controlTypeId,
        isClear: false,
        defValue: col.defaultValue,
        placeholder: '请填写' + col.cnName,
        title: col.cnName
      }
      colMeta[col.columnId] = meta
      findMeta.itemMeta[col.columnId] = meta
      findMeta.allFind.push(col.columnId)

      if (findMeta.quickFind.length < 5) {
        findMeta.quickFind.push(col.columnId)
      }
    })
  }

  watch(state.current.table.cols, (cols) => {
    clearTimeout(state.timeoutFind)
    state.timeoutFind = setTimeout(() => {
      _toMetaCol(cols)
      console.log('创建一次查询 meta')  
    }, 130)
  })

  return {
    findMeta,
    colMeta
  }
}